#Python's container pattern matching
#Pattern Matching with Tuples or Lists
Using a tuple or list pattern allows you to match against tuples or lists:
students: list[str] = ["Tom", "Jerry", "Spike"]
match students:
case (student1, student2): # Match tuple or list with two elements
print("There are two students:", student1, student2)
case (_, _, _, _, *other): # Match tuple or list with four or more elements
print("There are more than four students:", students)
case ("Tuffy", student1, student2): # Match three elements where the first is 'Tuffy'
print("Students sitting behind Tuffy are:", student1, student2)
case (student1, student2, "Spike"): # Match three elements where the last is 'Spike'
print("Students sitting in front of Spike are:", student1, student2)
case _:
print("BBQ")
Patterns can be written as tuples, lists, or sequences (without parentheses). Regardless of form, the pattern does not distinguish between tuples and lists—either can match both.
To distinguish between them, you can combine other patterns:
students: list[str] = ("Tom", "Jerry", "Spike")
match students:
case tuple((student1, student2, student3)): # Outer parentheses for function call, inner for tuple pattern
print("A tuple with three elements")
case list((student1, student2, student3)):
print("A list with three elements")
case _:
print("BBQ")
#Pattern Matching with Dictionaries
You can match dictionaries using dictionary-style patterns:
score_list: dict[str, int] = {
'Tom': 88,
'Jerry': 99,
'Spike': 66
}
match score_list:
case {"Tuffy": score}: # Match if dictionary has key 'Tuffy'
print("Tuffy's score is", score)
case {"Jerry": str(score)}: # Match if 'Jerry' has a string value
print("Jerry's score is", score)
case {"Tom": 88, "Jerry": score}: # Match if 'Tom' has score 88 and contains 'Jerry'
print("On the exam where Tom scored 88, Jerry's score was", score)
case _:
print("BBQ")
#Pattern Matching with Sets
Sets cannot be used as patterns. Only an empty set can be used to check if a variable is a set—but it’s easier to use if or isinstance:
students: set[str] = {"Tom", "Jerry", "Spike"}
match students:
case set():
print("It’s a set")